using DG.Tweening;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class RemoteController : MonoBehaviour, IPointerClickHandler
{
    public Character character;
    private Vector2 _taragetPos;
    private Vector2 _taragetScale;
    private TextMeshProUGUI _textCounter;

    void Awake()
    {
        character = GetComponent<Character>();
        _textCounter = transform.FindChildEx("InputCounter").GetComponent<TextMeshProUGUI>();
        _textCounter.color = new Color(1f, 1f, 1f, 0f);

        var canvasGroup = this.gameObject.AddComponent<CanvasGroup>();
        var alpha = GameSetting.Instance.settingData.alpha;
        canvasGroup.alpha = alpha;
        character.EnableRaycast(alpha > 0);

        EventMgr.Instance.RegisterEvent(EventType.AlphaChanged, OnAlphaChanged);
    }

    void OnDestroy()
    {
        EventMgr.Instance.RemoveEvent(EventType.AlphaChanged, OnAlphaChanged);
    }

    void Update()
    {
        // 插值
        character.SetPosition(Vector2.Lerp(character.GetPosition(), _taragetPos, Time.deltaTime * 10));
        character.SetScale(Vector2.Lerp(character.GetScale(), _taragetScale, Time.deltaTime * 10));
    }

    public void ApplyState(PlayerState state, bool isImmediate = false)
    {
        _taragetPos = new Vector2(state.Pos.X, state.Pos.Y);
        _taragetScale = new Vector2(state.Scale.X, state.Scale.Y);
        if (isImmediate)
        {
            character.SetPosition(_taragetPos);
            character.SetScale(_taragetScale);
        }
        character.SetState((CharacterState)state.Anim);

        _textCounter.text = state.Count.ToString();
    }

    private void OnAlphaChanged(Message message){
        var alpha = GameSetting.Instance.settingData.alpha;
        GetComponent<CanvasGroup>().alpha = alpha;
        character.EnableRaycast(alpha > 0.1);
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        var counterText = _textCounter;
        DOTween.Kill(counterText);
        counterText.color = new Color(1f, 1f, 1f, 1f);
        counterText.DOFade(0, 0.8f).SetDelay(5).Play();
    }
}